package com.guoliang.viewcount.aspect;

import com.guoliang.viewcount.aop.ViewCount;
import com.guoliang.viewcount.utils.ViewCountRedisUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author ：Leo
 * @date ：Created in 2023/2/5 12:04
 * @description：
 */
@Aspect
@Configuration
public class QuestionViewAspect {
    @Resource
    ViewCountRedisUtils redisUtils;
    @Resource
    RedisTemplate redisTemplate;
    @Pointcut("@annotation(com.guoliang.viewcount.aop.ViewCount)")
    public void questionViewPointCut(){}
    HttpServletRequest servletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Before("questionViewPointCut()")
    public Object before (JoinPoint joinPoint) throws Throwable{
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ViewCount annotation = signature.getMethod().getAnnotation(ViewCount.class);
        System.out.println(annotation.description());
        String ip=servletRequest().getRemoteHost();
        String id=(String) joinPoint.getArgs()[0];
        String key= annotation.description()+":"+id;
        String value=ip;
        redisUtils.add(key,value);
        System.out.println(redisUtils.size(key));
        return "";
    }
}
